package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) {
        // 1.检查参数
        if (file == null || file.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到minio中  TODO
        // 随机生成文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");
        // 获取文件后缀名
        String originalFilename = file.getOriginalFilename();//文件原始名
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));//文件后缀名

        String fileId = null;
        try {
            fileId = fileStorageService.uploadHtmlFile("", fileName + postfix, file.getInputStream());
            log.info("上传文件到minio中，fileId：{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件到minio中失败");
        }

        // 3.保存图片信息到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //TODO
        // 1.检查参数
        dto.checkParam();

        // 2.分页查询
        IPage<WmMaterial> iPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lqw = new LambdaQueryWrapper<>();

        // 是否收藏
        if (dto.getIsCollection() != null) {
            lqw.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        // 根据当前用户id查询
        lqw.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId()); // 用户id

        // 时间倒序查询
        lqw.orderByDesc(WmMaterial::getCreatedTime);

        // 查询
        page(iPage, lqw);

        // 3.返回
        ResponseResult<List<WmMaterial>> result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        result.setData(iPage.getRecords());
        return result;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
        //TODO 业务幂等
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial != null) {
            removeById(id);
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        //TODO
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial != null) {
            wmMaterial.setIsCollection((short) 0);
            updateById(wmMaterial);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        //TODO
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial != null) {
            wmMaterial.setIsCollection((short) 1);
            updateById(wmMaterial);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
